package it.interazionemultimodale.twitterrecognizer.ui;

import it.interazionemultimodale.twitterrecognizer.twitterutility.TwitterManager;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;

public class AuthorizationActivity extends Activity
{
	private WebView webView;
	private ProgressDialog progressDialog;
	
	private class ProgressDialogWebViewClient extends WebViewClient
	{	
		@Override
		public void onLoadResource(WebView view, String url)
		{
			//super.onLoadResource(view, url);
			if (url.startsWith("twitter-client:///") && !url.startsWith("twitter-client:///?denied"))
			{
				view.setVisibility(View.INVISIBLE);
				Context context = view.getContext();
				TwitterManager.saveAccountAndLoadHome(url, context, new Intent(context, HomeActivity.class));
			}
			/*else if (url.startsWith("twitter-client:///?denied") || url.startsWith("http://about:blank"))
			{
				//TODO: Gestire la pagina vuota o annullamento del login
			}*/
		}
		
		@Override
		public void onPageFinished (WebView view, String url)
		{
			super.onPageFinished(view, url);
			progressDialog.dismiss();
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		//Setting the webView where the login page will be loaded
		this.webView = new WebView(this);
		this.webView.setWebViewClient(new ProgressDialogWebViewClient());
		setContentView(webView);
		
		//Setting a progress dialog during the wait
		this.progressDialog = new ProgressDialog(this);
		this.progressDialog.setMessage("Caricamento in corso...");
		this.progressDialog.setCancelable(false);
		this.progressDialog.show();

		TwitterManager.loadLoginWebPage(this.webView);
	}
	
	@Override
	protected void onDestroy()
	{
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeSessionCookie();
		TwitterManager.logout();
		super.onDestroy();
	}
}
